import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AdminView from '../views/AdminView.vue'
import LoginView from '../views/LoginView.vue'
import { useUserStore } from '../stores/modules/user'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: '',
          redirect: '/home/search',
        },
        {
          path: 'search',
          name: 'search',
          component: () => import('../views/guest/SchoolFacility.vue'),
        },
        {
          path: 'distance',
          name: 'distance',
          component: () => import('../views/guest/DistanceAnalysis.vue'),
        },
        {
          path: 'route',
          name: 'route',
          component: () => import('../views/guest/RouteAnalysis.vue'),
        },
        {
          path: 'statistic',
          name: 'statistic',
          component: () => import('../views/guest/StatisticAnalysis.vue'),
        },
        {
          path: 'road-map',
          name: 'road-map',
          component: () => import('../views/guest/RoadMapView.vue'),
        }
      ],
    },
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/admin',
      name: 'admin',
      component: AdminView,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login',
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = userStore.isLoggedIn

  // 登录页面和公共道路地图页面可以直接访问
  if (to.path === '/login' || to.path === '/road-map') {
    next()
    return
  }

  // 未登录时重定向到登录页
  if (!isLoggedIn) {
    next('/login')
    return
  }

  // 根据用户类型控制页面访问权限
  if (to.path.startsWith('/admin') && !userStore.isAdmin) {
    // 非管理员不能访问管理页面
    next('/home')
    return
  }

  // 其他情况正常放行
  next()
})

export default router
